import {removeCookie} from './cookie'
import warterMark from '@/assets/js/watermark'
import router from '@/router'
import config from '../config'

let util = {
  /**
   * 产生一个唯一的uuid
   * @param len 产生的字符串长度
   * @param radix 进制数
   */
  getUUID(len, radix) {
    let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    let uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) {
        uuid[i] = chars[0 | Math.random() * radix];
      }
    } else {
      let r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  },
  /**
   * 日期格式化
   * @param fmt   转化格式
   * @param dateStr   时间
   * @Date: 2017/12/8
   */
  dateFormat(dateStr, fmt) {
    if (!dateStr) {
      return ""
    }
    let date = new Date(dateStr);
    let o = {
      "M+": date.getMonth() + 1,                 //月份
      "d+": date.getDate(),                    //日
      "h+": date.getHours(),                   //小时
      "m+": date.getMinutes(),                 //分
      "s+": date.getSeconds(),                 //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S": date.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  },

  /**
   * 时间戳格式化
   * @param fmt        转化格式
   * @param timeStamp   时间戳
   * @Date: 2017/12/8
   */
  timeFormat(timeStamp, fmt) {
    if (!timeStamp) {
      return ""
    }
    let date = new Date();
    if (timeStamp.length === 10) {
      date.setTime(timeStamp * 1000);
    }
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute = date.getMinutes();
    let second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return this.dateFormat(y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second, fmt);
  },
  /**
   * histroy模式 @param:url中所要提取的参数名
   * @author chenyi
   * @Date: 2019/08/22
   */
  getQueryParams(paramName){
    let reg = new RegExp('(^|&)' + paramName + '=([^&]*)(&|$)')
    let r = window.location.search.substr(1).match(reg)
    if (r != null) return unescape(r[2])
    return null
  },
  /**
   * hash模式 @param:url中所要提取的参数名
   * @author chenyi
   * @Date: 2019/08/22
   */
  getUrlParams(paramName){
    let url = document.location.toString()
    let arrObj = url.split('?')
    if (arrObj.length > 1) {
      let arrPara = arrObj[1].split('&')
      let arr
      for (let i in arrPara) {
        arr = arrPara[i].split('=')
        if (arr != null && arr[0] === paramName) {
          return arr[1]
        }
      }
      return ''
    } else {
      return ''
    }
  },
  /**
   * 清除登录信息
   * @author chenyi
   * @Date: 2019/08/22
   */
  clearLoginInfo(){
    removeCookie('token')//删除token
    warterMark.set('')//清除水印
    router.options.isAddDynamicMenuRoutes = false
  },
  /**
   * 获取前端缓存
   * @author chenyi
   * @Date: 2019/05/22
   */
  getLocalStorageItem(key){
    return JSON.parse(localStorage.getItem(key))
  },
  /**
   * 设置前端缓存
   * @author chenyi
   * @Date: 2019/05/22
   */
  setLocalStorageItem(key, data){
    localStorage.setItem(key, JSON.stringify(data))
  },
  /**
   * 值转义
   * @author chenyi
   * @Date: 2019/05/22
   */
  getDictValue(list,value){
    for (let item in list) {
      if (list[item].value == value) {
        return list[item].label

      }
    }
  },
  /**
   * 颜色渲染
   *@param index 颜色数组下标
   *@params text 要渲染的文本
   */
  renderColor(index,text) {
    let color = config.colors[index];
    return `<span style="color:${color}">${text}</span>`
  }
}
//js方法格式化数字，加入千分符
util.fmoney = function(s) {
  if (s == '*') {
    return s;
  }

  var n = 2;
  n = n >= 0 && n <= 20 ? n : 2;
  s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  var l = s
      .split(".")[0]
      .split("")
      .reverse(),
    r = s.split(".")[1];
  r = r == null ? "" : "." + r;
  var t = "";
  ////console.log(l)
  if (l[l.length - 1] === '-') {//负数不需要分隔号,

    for (var i = 0; i < l.length; i++) {
      if (l[i] === '-') {
        t += l[i] + ""
        continue
      }
      //不是数组的倒数第二个元素才加"," ["0", "4", "5", "-"]
      t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length - 1 ? "," : "");

      //i + 1 != l.length会变成-,540.00,因为在5时元素位置2+1为3非数组长度
      //t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
    }
  }
  else {
    for (var i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
    }
  }
  return (
    t
      .split("")
      .reverse()
      .join("") + r
  );


}
//排序规则
util.sortby= function  (name, minor, sort) {
  return function (o, p) {
    var a, b;
    if (o && p && typeof o === 'object' && typeof p === 'object') {
      a = o[name];
      b = p[name];
      if (a === b) {
        return typeof minor === 'function' ? minor(o, p) : 0;
      }
      if (typeof a === typeof b) {
        a = parseFloat(a.toString().replace(/,/g, ''));
        b = parseFloat(b.toString().replace(/,/g, ''));
        if (sort == 'ascending') {
          return a < b ? -1 : 1;
        } else if (sort == 'descending') {
          return a < b ? 1 : -1;
        }

      }
      if (sort == 'ascending') {
        return typeof a < typeof b ? -1 : 1;
      } else if (sort == 'descending') {
        return typeof a < typeof b ? 1 : -1;
      }

    } else {
      throw("error");
    }
  }
}

export default util;



